<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";

export default {

  inject: ["reload"],

  data() {
    return {
      // 搜索条件
      searchQuery: {
        type_code: "",
        type_name: ""
      },
      // 数据列表
      dicTypeList: [],
      // 总条数
      total: 0,
      // 每页显示多少条数据
      pageSize: 10,
      // 当前页码
      currentPage: 1,
      // 弹窗显示状态
      dialogVisible: false,
      // 弹窗标题
      dialogTitle: "添加字典类型",
      // 表单数据
      formData: {
        id: null,
        typeCode: "",
        typeName: "",
        remark: ""
      },
      // 表单验证规则
      formRules: {
        typeCode: [
          {
            required: true,
            message: "请输入字典类型代码",
            trigger: "blur"
          },
          {
            pattern: /^[A-Za-z]+$/,
            message: "字典类型代码只能包含英文字符",
            trigger: "blur"
          }
        ],
        typeName: [
          {required: true, message: "请输入字典类型名称", trigger: "blur"}
        ],
        remark: [
          {required: true, message: "请输入备注", trigger: "blur"}
        ]
      },
      // 选择的产品id数组
      productIdArray: [],
    };
  },
  methods: {
    // 查询字典类型列表
    getData(current) {
      doGet("/api/dict-types", {
        current: current,
        typeCode: this.searchQuery.type_code,
        typeName: this.searchQuery.type_name,
      }).then(resp => {
        if (resp.data.code === 200) {
          this.dicTypeList = resp.data.data.list;
          this.total = resp.data.data.total;
          this.pageSize = resp.data.data.pageSize;
        }
      });
    },
    // 分页切换
    toPage(page) {
      this.getData(page);
    },

    // 查询
    onSearch() {
      this.getData(1); // 查询时从第一页开始
    },

    // 重置
    onReset() {
      this.searchQuery = {
        type_code: "",
        type_name: ""
      };
      this.getData(1);
    },

    // 打开添加弹窗
    add() {
      this.dialogVisible = true;
      this.dialogTitle = "添加字典类型";
      this.formData = {id: null, type_code: "", type_name: "", remark: ""};
    },

    // 打开编辑弹窗
    edit(id) {
      doGet("/api/dict-type/" + id).then(resp => {
        if (resp.data.code === 200) {
          this.dialogVisible = true;
          this.dialogTitle = "编辑字典类型";
          this.formData = resp.data.data;
        }
      });
    },

    // 删除字典类型
    del(id) {
      messageConfirm("确定要删除该字典类型吗?").then(() => {
        doDelete("/api/dict-type/" + id).then(resp => {
          if (resp.data.code === 200) {
            messageTip("删除成功", "success");
            this.getData(this.currentPage); // 删除后重新加载数据
            this.reload();
          } else {
            messageTip("删除失败", "error");
          }
        });
      }).catch(() => {
        messageTip("取消删除", "warning");
      });
    },

    // 保存表单数据（添加或编辑）
    saveFormData() {
      this.$refs.dicTypeEditForm.validate((valid) => {
        if (valid) {
          if (this.formData.id) {
            // 编辑字典类型
            doPut("/api/dict-type/edit", this.formData).then(resp => {
              if (resp.data.code === 200) {
                messageTip("修改成功", "success");
                this.dialogVisible = false;
                this.getData(this.currentPage);
                this.reload();
              } else {
                messageTip("修改失败", "error");
              }
            });
          } else {
            // 添加字典类型
            doPost("/api/dict-type/add", this.formData).then(resp => {
              if (resp.data.code === 200) {
                messageTip("添加成功", "success");
                this.dialogVisible = false;
                this.getData(this.currentPage);
                this.reload();
              } else {
                messageTip("添加失败", "error");
              }
            });
          }
        } else {
          messageTip("表单验证失败，请检查输入内容", "warning");
        }
      });
    },

    // 批量删除
    batchDelete() {
      if (this.productIdArray.length <= 0) {
        messageTip("请选择要删除的字典类型", "warning");
        return;
      }
      messageConfirm("确定要删除这些字典类型吗?").then(() => {
        let ids = this.productIdArray.join(",");
        doDelete("/api/dict-types/batch-delete", {ids: ids}).then(resp => {
          if (resp.data.code === 200) {
            messageTip("批量删除成功", "success");
            this.getData(this.currentPage); // 删除后重新加载数据
            this.reload();
          } else {
            messageTip("批量删除失败，原因：" + resp.data.msg, "error");
          }
        });
      }).catch(() => {
        messageTip("取消批量删除产品", "warning");
      });
    },

    // 处理表格选择
    handleSelectionChange(selectionDataArray) {
      this.productIdArray = selectionDataArray.map(item => item.id);
    }
  },
  mounted() {
    this.getData(1); // 初始化加载第一页数据
  }
};
</script>


<template>
  <div>
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchQuery" style="margin-bottom: 20px;">
      <el-form-item label="字典类型代码">
        <el-input v-model="searchQuery.type_code" placeholder="请输入字典类型代码" clearable/>
      </el-form-item>
      <el-form-item label="字典类型名称">
        <el-input v-model="searchQuery.type_name" placeholder="请输入字典类型名称" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="add">添加字典类型</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>

    <!-- 数据展示表格 -->
    <el-table :data="dicTypeList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column type="index" label="序号" width="60"/>
      <el-table-column property="typeCode" label="字典类型代码"/>
      <el-table-column property="typeName" label="字典类型名称"/>
      <el-table-column property="remark" label="备注"/>
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button type="primary" size="mini" @click="edit(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize" @current-change="toPage"/>

    <!-- 编辑/添加字典类型弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="55%" center>
      <el-form ref="dicTypeEditForm" :model="formData" label-width="120px" :rules="formRules">
        <el-form-item label="字典类型代码" prop="typeCode">
          <el-input v-model="formData.typeCode" placeholder="请输入字典类型代码"/>
        </el-form-item>
        <el-form-item label="字典类型名称" prop="typeName">
          <el-input v-model="formData.typeName" placeholder="请输入字典类型名称"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveFormData">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.el-pagination {
  margin-top: 20px;
}
</style>
